// stores/user.js
import { defineStore } from "pinia";
import api from "@/api";

export const useUserStore = defineStore("user", {
  state: () => ({
    userInfo: {
      nickname: "加载中...",
      avatar: "",
      account: "",
      name: "",
      phone: "",
      email: "",
      idCard: "",
      description: "",
      sex: "",
      hobby: "",
      job: "",
      roles: [],
    },
    loading: false,
    error: null,
  }),
  actions: {
    async fetchUserInfo() {
      this.loading = true;
      this.error = null;

      try {
        const { data } = await api.user.getUserInfo();
        this.setUserInfo({
          nickname: data.nickname || "未设置昵称",
          avatar:
            "http://localhost:8080" + data.avatar || "/default-avatar.png",
          account: data.account,
          name: data.name,
          phone: data.phone,
          email: data.email,
          idCard: data.idcard,
          description: data.description || "暂无简介",
          sex: data.gender || data.sex,
          hobby: data.hobbies || data.hobby,
          job: data.occupation || data.job,
          roles: data.roles || [],
        });
      } catch (error) {
        this.error = error;
        throw error;
      } finally {
        this.loading = false;
      }
    },

    setUserInfo(info) {
      this.userInfo = {
        ...this.userInfo,
        ...info,
      };
      // 持久化存储
      localStorage.setItem("userInfo", JSON.stringify(this.userInfo));
    },

    clearUserInfo() {
      this.userInfo = {
        nickname: "未登录",
        avatar: "",
        account: "",
        name: "",
        phone: "",
        email: "",
        idCard: "",
        description: "",
        sex: "",
        hobby: "",
        job: "",
        roles: [],
      };
      localStorage.removeItem("userInfo");
    },
  },
});
